import { GlobalVariable, HttpUrlVariable, PAGE_PATH } from '@/constants'
import { useTokenStore } from '@/store/token'
import type { ResponeseData } from '@/types/common'
import Request from 'luch-request'
import type { HttpData, HttpParams, HttpRequestConfig, HttpTask } from 'luch-request'

// const instance = axios.create()
const instance = new Request({
  baseURL: GlobalVariable.BASE_URL,
  timeout: GlobalVariable.TIME_OUT,
}) // new的时候做了什么事情
const whiteList: string[] = [
  HttpUrlVariable.LOGIN_CODE_URL,
  HttpUrlVariable.LOGIN_URL,
  HttpUrlVariable.SEND_CODE_URL,
]
// 请求拦截器
instance.interceptors.request.use(
  (config: HttpRequestConfig<HttpTask>) => {
    // 开启进度条
    uni.showLoading({
      title: GlobalVariable.LOADING_TEXT,
      mask: true,
    })
    // 判断一下当前请求的地址在不在白名单里面在的话，不用传token
    // 注入token
    console.log(config.url)
    const store = useTokenStore()
    if (!whiteList.includes(config.url as string) && store.getToken()) {
      // 注入token
      config.header!.Authorization = `Bearer ${store.getToken()}` // 注入token操作
    }

    return config
  },
  (error) => Promise.reject(error)
)
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const result = response.data as ResponeseData
    uni.hideLoading()
    if (result.code === GlobalVariable.SUCCESS_CODE) {
      return result.data
    }
    uni.showToast({
      title: result.message,
      icon: 'none',
    })
    return Promise.reject(new Error(result.message))
  },
  (error) => {
    uni.hideLoading()
    console.log(error.statusCode)
    if (error.statusCode === 401) {
      // token失效或者没传
      const store = useTokenStore()
      store.removeToken() // 删除token
      uni.reLaunch({ url: PAGE_PATH.LOGIN_PAGE })
    }
    // 弹出错误信息
    uni.showToast({
      title: error.data && error.data.message ? error.data.message : error.errMsg,
      icon: 'none',
    })

    return Promise.reject(error)
  }
)

export default class RequestHttp {
  // 查询数据
  // P要满足HttpParams的类型约束
  // P的类型满足HttpParams的要求
  static get<T, P extends HttpParams = object>(url: string, params?: P) {
    return instance.get<null, T>(url, { params })
  }
  // 新增数据/登录
  static post<T, P extends HttpData = object>(url: string, data?: P) {
    return instance.post<null, T>(url, data)
  }
  // 修改
  static put<T, P extends HttpData = object>(url: string, data?: P) {
    return instance.put<null, T>(url, data)
  }
  // 删除
  static delete<T, P extends HttpParams = object>(url: string, params?: P) {
    return instance.delete<null, T>(url, { params })
  }
  // 底层upload方法
  // luch-request支持上传方法
  static upload<T>(url: string, data: string) {
    return instance.upload<null, T>(url, {
      name: 'file', // 接口的name对应的key值
      filePath: data, // 要上传的文件路径- luch-request会在底层改成file对象(base64)
    })
  }
}
